package com.hornsun.admin;

import com.hornsun.config.ConfigInfo;
import com.hornsun.data.constant.error.AccountError;
import com.hornsun.data.constant.error.CommonError;
import com.hornsun.data.dbo.Client;
import com.hornsun.data.repository.ClientRepository;
import com.hornsun.util.CaptchaUtil;
import com.hornsun.util.DESUtil;
import com.hornsun.util.RSAUtils;
import com.hornsun.client.api.ClientAPI;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * Created by 编译中... on 2018/7/4.
 */
@RestController
@RequestMapping("/admin")
public class Admin {

    @Autowired
    private ClientRepository clientRepository;

    @Autowired
    private ConfigInfo configInfo;

    @PostMapping("/login")
    public ResponseEntity<?> login(HttpSession httpSession,
                                   @RequestParam("account")String account1,
                                   @RequestParam("password")String rsaPassword,
                                   @RequestParam("code")String code) throws Exception {
        String verificationCode = (String)httpSession.getAttribute("code");
        if(code==null||code.isEmpty()){
            return new ResponseEntity<Object>(AccountError.VERIFICATION_CODE_ERROR.getCode(),HttpStatus.OK);
        }
        if (!(code.toUpperCase()).equals(verificationCode)){
            return new ResponseEntity<Object>(AccountError.VERIFICATION_CODE_ERROR.getCode(),HttpStatus.OK);
        }
        String account = (String) httpSession.getAttribute("Account");
        Client client = new Client();
        if (account==null){
                String password  = new String(RSAUtils.decryptByPrivateKey(Base64.decodeBase64(rsaPassword.replace("%2B","+")),RSAUtils.getPrivateKey()));
                String desPassword = DESUtil.encrypt(password);
                if (clientRepository.checkAccountInfo(account1,desPassword)){
                    if (DESUtil.encrypt(configInfo.getInitialPassword()).equals(desPassword)){
                        return new ResponseEntity<Object>(AccountError.INIT_PASSWORD.getCode(),HttpStatus.OK);
                    }
                    httpSession.setAttribute("Account", account1);
                    clientRepository.updateByAccount(client,account1);
                    return new ResponseEntity<Object>(account1, HttpStatus.OK);
                }else {
                    return new ResponseEntity<Object>(AccountError.ACCOUNT_OR_PASSWORD_ERROR.getCode(), HttpStatus.OK);
                }

        }
        clientRepository.updateByAccount(client,account);
        return new ResponseEntity<Object>(account1,HttpStatus.OK);
    }

    @GetMapping("/getWhetherLogin")
    public ResponseEntity<?> getWhetherLogin(HttpSession httpSession){
        String account = (String) httpSession.getAttribute("Account");
        if (account==null||account.isEmpty()||"".equals(account)){
            return new ResponseEntity<Object>(false,HttpStatus.OK);
        }
        return new ResponseEntity<Object>(true,HttpStatus.OK);
    }

    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpSession httpSession) {
        httpSession.invalidate();
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    @GetMapping("/getVerification")
    public void getVerification(HttpServletRequest request,HttpServletResponse response) throws Exception {
        // 通知浏览器不要缓存
        response.setHeader("Expires", "-1");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "-1");
        CaptchaUtil util = CaptchaUtil.instance();
        // 将验证码输入到session中，用来验证
        String code = util.getString();
        request.getSession().setAttribute("code", code.toUpperCase());
        // 输出打web页面
        try {
            ImageIO.write(util.getImage(), "jpg", response.getOutputStream());
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    /**
     * 修改初始密码
     * @param httpSession
     * @param newPwd
     * @param pwdAgain
     * @return
     * @throws Exception
     */
    @PostMapping("/updateInitPassword")
    public ResponseEntity<?> updatePassword(HttpSession httpSession,
                                            @RequestParam("account") String account,
                                            @RequestParam("newPwd")String newPwd,
                                            @RequestParam("pwdAgain")String pwdAgain) throws Exception {
        if (account==null||account.isEmpty()||newPwd==null||newPwd.isEmpty()||pwdAgain==null||pwdAgain.isEmpty()){
            return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
        }
        Client client = clientRepository.getByAccount(account);
        if (client==null){
            return new ResponseEntity<Object>(CommonError.NOT_EXIST.getCode(),HttpStatus.OK);
        }
        if (!DESUtil.encrypt(configInfo.getInitialPassword()).equals(client.getPassword())){
            return new ResponseEntity<Object>(AccountError.NOT_INIT_PASSWORD.getCode(),HttpStatus.OK);
        }
        String pwd =  new String(RSAUtils.decryptByPrivateKey(Base64.decodeBase64(newPwd.replace("%2B","+")),RSAUtils.getPrivateKey()));
        String regex ="^[a-zA-Z\\d]{6,16}$";
        if (!pwd.matches(regex)){
            return new ResponseEntity<Object>(AccountError.PASSWORD_FORMAT_ERROR.getCode(),HttpStatus.OK);
        }
        if (!ClientAPI.pwdWhetherSame(newPwd,pwdAgain)){
            return new ResponseEntity<Object>(AccountError.TWO_PASSWORD_DIFFERENT.getCode(),HttpStatus.OK);
        }

        String newPassword  = DESUtil.encrypt(pwd);
        if(newPassword.equals(client.getPassword())){
            return new ResponseEntity<Object>(AccountError.SAME_WITH_OLD.getCode(),HttpStatus.OK);
        }
        client.setPassword(newPassword);
        clientRepository.updateClient(client);
        return new ResponseEntity<Object>(HttpStatus.OK);

    }


}
